<template>
	<view class="relayPage">
		<nav-bar title="灌区运行管理"></nav-bar>
		<van-skeleton title :row="10" />
	</view>
</template>

<script setup>
	import store from '@/store';
	import { config } from '@/common/config';
	import {
		apiTicketLoginTest,
		apiTicketToken,
		apiDelTicketToken,
		apiGetUserInfo
	} from '@/api/common';
	const path = defineProps({
		ticket: String,
	});
	const ticketTest = path.ticket || config.ticket;
	
	uni.showLoading({
		title: '登录中'
	});

	const getUserInfo = () => {
		apiGetUserInfo().then(res => {
			store.dispatch('setUserInfo', res);
		})
	}

	// 单点登陆
	const getTicketToken = async () => {
		try {
			// 清理token
			await apiDelTicketToken();
		} catch (error) {}

		// 获取单点登陆需要的信息
		apiTicketLoginTest(ticketTest).then(res => {
			// 获取token
			apiTicketToken({
				mobile: res.mobile,
				code: res.code,
				scope: res.scope,
				grant_type: res.grantType
			}).then(async r => {
				// 保存access_token 和 refresh_token
				await store.dispatch('setAccessToken', r.access_token);
				await store.dispatch('setRefreshToken', r.refresh_token);
				await store.dispatch('appStore/setAppInfo');
				
				await store.dispatch('setMessageNumbers');
				getUserInfo();
				
				uni.hideLoading();
				uni.switchTab({
					url: '/pages/home/index'
				})
			}).catch(() => {
				uni.hideLoading();
				uni.navigateTo({ url: '/pages/relayPage/fail' })
			})
		}).catch(() => {
			uni.hideLoading();
			uni.navigateTo({ url: '/pages/relayPage/fail' })
		})
	}

	getTicketToken();
</script>

<style scoped></style>